package com.xtgg.main;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.baby.BabyBoundListActivity;
import com.xtgg.baby.DeviceListActivity;
import com.xtgg.baby.DeviceSearchActivity;
import com.xtgg.login.SetPasswordActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.more.AddNewBabyActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.ImageLoaderHelper;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;
import com.xtgg.util.Utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MainPageActivity extends BaseActivity implements OnClickListener,OnGestureListener,OnTouchListener {
	static public JSONArray mArray = null;
	ArrayList<JSONObject> mDeviceArray = new ArrayList<JSONObject>();
	
	ViewTreeObserver.OnPreDrawListener listen = null;
	BleReceiver mReceiver;
	
	boolean mIsDis = false;
	boolean mIsConnect = false;
	public static boolean mManulDisconnect = false;
	
	static public int mSelected = -1;
	
	public class BleReceiver extends BroadcastReceiver
	{
		@SuppressLint("NewApi")
		public void onReceive(Context paramContext, Intent paramIntent)
	    {
			if (paramIntent.getAction().equals("com.fb.ble.action.device_connect"))
			{
				if(mArray == null || mArray.size() == 0) return; 
				
				if(((DemoApp)getApplicationContext()).mSafeArray.contains(
						String.valueOf(mArray.getJSONObject(mSelected).getString("childid"))) && !mManulDisconnect)
				{
					((DemoApp)getApplicationContext()).mSafeArray.remove(
							String.valueOf(mArray.getJSONObject(mSelected).getString("childid")));
				}	
				
				disMissDailog();
				if(paramIntent.getStringExtra("connect").equals("1")) mIsConnect = true;
				else
				{
					mIsConnect = false;
				}
				
				changeStatus();
				if(mTimer != null)
				{
					mTimer.cancel();
					mTimer = null;
				}
				
				if(mArray == null || mArray.getJSONObject(mSelected) == null) return;
				
				JSONArray array = mArray.getJSONObject(mSelected).getJSONArray("devices");
				int count = array.size();
				for(int i = 0; i < count; i++)
				{
					if(paramIntent.getStringExtra("address").equals(array.getJSONObject(i).getString("andriod_code")))
					{
						sendHttpRequest(array.getJSONObject(i).getString("deviceid"));
					}
				}
			}
	    }
	}
	
	private void sendHttpRequest(String deviceid) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
				}
				else if (ruser.getString("state").equals("2")) 
				{
					showExitDialog();
				} 
				else {
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "operateDevice");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("deviceid",deviceid);
		params.put("childid", mArray.getJSONObject(mSelected).getString("childid"));
		if(mIsConnect) params.put("type", "0");
		else params.put("type", "1");
		MgqRestClient.post(Constants.DEVICEMGT, params, loginHandler);
	}
	
	protected void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}
	
	protected void onStop()
	{
		super.onStop();
		mManulDisconnect = false;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_page);
		
		mSelected = -1;
		mArray = null;
		
		mReceiver = new BleReceiver();
		IntentFilter localIntentFilter = new IntentFilter();
	    localIntentFilter.addAction("com.fb.ble.action.device_connect");
	    registerReceiver(mReceiver, localIntentFilter);

		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.action1).setOnClickListener(this);
		findViewById(R.id.c_icon).setOnClickListener(this);

		findViewById(R.id.l_icon).setVisibility(View.INVISIBLE);
		findViewById(R.id.c_icon).setVisibility(View.INVISIBLE);
		findViewById(R.id.r_icon).setVisibility(View.INVISIBLE);
		
		mGestureDetector = new GestureDetector(this);
		findViewById(R.id.slider).setOnTouchListener(this);
		
		showA();
	}
	
	void showA()
	{
		final Handler handle = new Handler()
		{
			public void handleMessage(Message msg)
			{
				if(findViewById(R.id.img0).getVisibility() == View.INVISIBLE)
					findViewById(R.id.img0).setVisibility(View.VISIBLE);
				else if(findViewById(R.id.img1).getVisibility() == View.INVISIBLE)
					findViewById(R.id.img1).setVisibility(View.VISIBLE);
				else if(findViewById(R.id.img2).getVisibility() == View.INVISIBLE)
					findViewById(R.id.img2).setVisibility(View.VISIBLE);
				else
				{
					findViewById(R.id.img0).setVisibility(View.INVISIBLE);
					findViewById(R.id.img1).setVisibility(View.INVISIBLE);
					findViewById(R.id.img2).setVisibility(View.INVISIBLE);
				}
			}
		};
		
		new Timer().schedule(new TimerTask()
		{
			@Override
			public void run() {
				handle.sendEmptyMessage(0);
			}
		}, 1000,1000);
	
	}
	
	protected void onResume()
	{
		super.onResume();
		sendHttpRequest();

		mManulDisconnect = false;
	}

    @SuppressLint("NewApi")
	void changeStatus()
	{
    	((Button) findViewById(R.id.right)).setText("相册");
    	
    	findViewById(R.id.c_icon).setVisibility(View.VISIBLE);
		if(mArray == null || mArray.size() == 0) 
		{
			((ImageView) findViewById(R.id.c_icon)).setImageResource(R.drawable.camera_normal);
			
			findViewById(R.id.head).setBackgroundColor(Color.parseColor("#8ac339"));
			((ImageButton) findViewById(R.id.action1)).setBackgroundResource(R.drawable.corner_green_m);
			((ImageButton) findViewById(R.id.action1)).setImageResource(R.drawable.ic_connect);

			((TextView) findViewById(R.id.name)).setText("你好，欢迎使用");
			((TextView) findViewById(R.id.name)).setTextColor(Color
					.parseColor("#aaaaaa"));
			((TextView) findViewById(R.id.addr)).setTextColor(Color
					.parseColor("#aaaaaa"));
			((TextView) findViewById(R.id.addr)).setText(Utils.ConverToString(new Date(), "yyyy年MM月dd日"));

			((TextView) findViewById(R.id.text1)).setText("添加设备");
			((TextView) findViewById(R.id.text1)).setTextColor(Color.parseColor("#8ac339"));
			
			return;
		}
		
		if(mSelected == -1) mSelected = 0;
		
		int size = mArray.size();
		if(mSelected == 0)
		{
			findViewById(R.id.l_icon).setVisibility(View.INVISIBLE);
		}
		else
		{
			findViewById(R.id.l_icon).setVisibility(View.VISIBLE);
			ImageLoaderHelper.displayImage(R.drawable.camera_normal,
					((ImageView)findViewById(R.id.l_icon)), mArray.getJSONObject(mSelected - 1).getString("headurl"));
		}
		
		if(mSelected == size - 1)
		{
			findViewById(R.id.r_icon).setVisibility(View.INVISIBLE);
		}
		else
		{
			findViewById(R.id.r_icon).setVisibility(View.VISIBLE);
			ImageLoaderHelper.displayImage(R.drawable.camera_normal,
					((ImageView)findViewById(R.id.r_icon)), mArray.getJSONObject(mSelected + 1).getString("headurl"));
		}
		
		JSONObject item = mArray.getJSONObject(mSelected);
		
		findViewById(R.id.c_icon).setVisibility(View.VISIBLE);
		((TextView) findViewById(R.id.name)).setText(item.getString("nickname"));
		ImageLoaderHelper.displayImage(R.drawable.camera_normal,(ImageView) findViewById(R.id.c_icon), 
				item.getString("headurl"));
		
		mDeviceArray.removeAll(mDeviceArray);
		mIsConnect = false;
		mIsDis = false;
		JSONArray array = item.getJSONArray("devices");
		int count = array.size();
		for(int i = 0; i < count; i++)
		{
			JSONObject obj = array.getJSONObject(i);
			List<BluetoothGatt> list = ((DemoApp)getApplicationContext()).deviceInfo;
			size = list.size();
			for(int j = 0; j < size; j++)
			{
				if(list.get(j).getDevice().getAddress().equals(obj.getString("andriod_code")))
				{
					mIsConnect = true;
				}
			}
			
			if(obj.getIntValue("d_status") == 0)
			{
				mIsDis = true;
			}
			
			if(obj.getInteger("status") != 3)
			{
				mDeviceArray.add(obj);
			}
		}
		
		boolean safe = false;
		try
		{
			if(((DemoApp)getApplicationContext()).mSafeArray.contains(
					String.valueOf(mArray.getJSONObject(mSelected).getString("childid"))))
			{
				safe = true;
			}	
		}catch(Exception e){}
		
		if(safe)
		{
			findViewById(R.id.head).setBackgroundColor(Color.parseColor("#f8c400"));

			((ImageButton) findViewById(R.id.action1)).setImageResource(R.drawable.ic_connect);
			((ImageButton) findViewById(R.id.action1)).setBackgroundResource(R.drawable.corner_orange_m);
			
			((TextView) findViewById(R.id.name)).setTextColor(Color.parseColor("#f8c400"));
			((TextView) findViewById(R.id.addr)).setTextColor(Color.parseColor("#f8c400"));
			((TextView) findViewById(R.id.addr)).setText("设备已设定为免打扰模式");
			((TextView) findViewById(R.id.text1)).setText("监控");
			((TextView) findViewById(R.id.text1)).setTextColor(Color.parseColor("#f8c400"));
			return;
		}

		((TextView) findViewById(R.id.text1)).setVisibility(View.VISIBLE);
		if(mDeviceArray.size() == 0)
		{
			findViewById(R.id.head).setBackgroundColor(Color.parseColor("#8ac339"));

			((ImageButton) findViewById(R.id.action1)).setImageResource(R.drawable.ic_connect);
			((ImageButton) findViewById(R.id.action1)).setBackgroundResource(R.drawable.corner_green_m);
			
			((TextView) findViewById(R.id.name)).setTextColor(Color.parseColor("#8ac339"));
			((TextView) findViewById(R.id.addr)).setTextColor(Color.parseColor("#8ac339"));
			((TextView) findViewById(R.id.text1)).setText("监控");
			((TextView) findViewById(R.id.text1)).setTextColor(Color.parseColor("#8ac339"));
		}
		else if (!mIsConnect) {
			findViewById(R.id.head).setBackgroundColor(
					Color.parseColor("#f74741"));

			((ImageButton) findViewById(R.id.action1))
					.setBackgroundResource(R.drawable.corner_red_m);
			((ImageButton) findViewById(R.id.action1)).setImageResource(R.drawable.ic_connect);

			((TextView) findViewById(R.id.name)).setTextColor(Color
					.parseColor("#f74741"));
			((TextView) findViewById(R.id.addr)).setTextColor(Color
					.parseColor("#f74741"));
			((TextView) findViewById(R.id.addr)).setText("失去连接");

			if(mIsDis) ((Button) findViewById(R.id.right)).setText("跟踪寻人");
			else ((Button) findViewById(R.id.right)).setText("发布寻人");
			((TextView) findViewById(R.id.text1)).setText("监控");
			((TextView) findViewById(R.id.text1)).setTextColor(Color.parseColor("#f74741"));
		}
		else
		{
			findViewById(R.id.head).setBackgroundColor(
					Color.parseColor("#8ac339"));

			((ImageButton) findViewById(R.id.action1))
					.setBackgroundResource(R.drawable.corner_green_m);

			((ImageButton) findViewById(R.id.action1)).setImageResource(R.drawable.ic_dis_connect);

			((TextView) findViewById(R.id.name)).setTextColor(Color
					.parseColor("#8ac339"));
			((TextView) findViewById(R.id.addr)).setTextColor(Color
					.parseColor("#8ac339"));
			((TextView) findViewById(R.id.addr)).setText(((DemoApp)this.getApplicationContext()).mAddress);
			((TextView) findViewById(R.id.text1)).setText("免打扰");
			((TextView) findViewById(R.id.text1)).setTextColor(Color.parseColor("#8ac339"));
		}
	}

    private void sendLostHttpRequest() {
		boolean show = true;
		if (mArray.size() > 0)
			show = false;
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					boolean result = false;
					
					ArrayList<JSONObject> array = ruser.data;
					for(JSONObject item : array)
					{
						if(item.getIntValue("child_id") == mArray.getJSONObject(mSelected).getIntValue("child_id"))
						{
							Intent intent = new Intent(MainPageActivity.this,SearchBabyActivity.class);
							intent.putExtra("baby", JSON.toJSONString(item));
							startActivity(intent);
							
							result = true;
						}
					}
					
					if(!result) ToastUtil.showToastWithAlertPic("您还未发布过寻人信息");
				} 
				else if (ruser.getState().equals("2")) 
				{
					showExitDialog();
				} 
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "myInfo");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		MgqRestClient.post(Constants.INFOMGT, params, loginHandler);
	}
    
    void showQuery() {
    	final Dialog mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_query);
		mDialog.findViewById(R.id.left).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.right).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
						startActivity(new Intent(MainPageActivity.this,DeviceSearchActivity.class));
					}
				});
		((TextView)mDialog.findViewById(R.id.content)).setText("该设备未与该手机配对，是否扫描连接？");
		mDialog.show();
    }
    
	@SuppressLint("NewApi")
	@Override
	public void onClick(View arg0) {
		mManulDisconnect = false;
		switch (arg0.getId()) {
		case R.id.c_icon:
		{
			if(mArray == null || mArray.size() == 0)
			{
				startActivity(new Intent(this, AddNewBabyActivity.class));
				break;
			}
			
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				Intent intent = new Intent(
						"android.media.action.IMAGE_CAPTURE");
				startActivityForResult(intent, 4);
			}
		}
			break;
			
		case R.id.right:
		{
			if(mArray != null && mArray.size() != 0 && mDeviceArray.size() != 0 && !mIsConnect) 
			{
				if(mIsDis)
				{
					sendLostHttpRequest();
				}
				else
				{
					Intent intent = new Intent(this, DistributeActivity.class);
					intent.putExtra("baby", mArray.getJSONObject(mSelected).toJSONString());
					startActivity(intent);
				}
			}
			else
			{
				if(mSelected == -1)
				{
					this.showToast("您还没有添加宝宝");
					return;
				}
				
				Intent intent = new Intent(this,PhotosActivity.class);
				intent.putExtra("childid", mArray.getJSONObject(mSelected).getString("childid"));
				startActivity(intent);
			}
		}
			break;
		
		case R.id.action1:
			if(mArray == null || mArray.size() == 0 || mDeviceArray.size() == 0) 
			{
				BluetoothAdapter.getDefaultAdapter().enable();
				startActivity(new Intent(this,DeviceSearchActivity.class));
			
				return;
			}
			
			boolean safe = false;
			try
			{
				if(((DemoApp)getApplicationContext()).mSafeArray.contains(
						String.valueOf(mArray.getJSONObject(mSelected).getString("childid"))))
				{
					safe = true;
				}		
			}catch(Exception e){}
			
			if(safe)
			{
				try{
					showWaiting("正在连接设备...");
					
					if(!BluetoothAdapter.getDefaultAdapter().isEnabled())
					{
						BluetoothAdapter.getDefaultAdapter().enable();
					}
					
					String andriod_code = mDeviceArray.get(0).getString("andriod_code");
					if(andriod_code == null || andriod_code.length() == 0)
					{
						showQuery();
					}
					else
					{
						BluetoothDevice localBluetoothDevice = ((DemoApp)getApplicationContext()).mBluetoothAdapter
								.getRemoteDevice(andriod_code);
						localBluetoothDevice.connectGatt(MainPageActivity.this, false, ((DemoApp)getApplicationContext()).mGattCallback);
						startTimer();
					}
				}
				catch(Exception e)
				{
					ToastUtil.showToastWithAlertPic("连接失败");
				}
				return;
			}
			
			if (!mIsConnect) {

				showWaiting("正在连接设备...");
				
				try{
					if(!BluetoothAdapter.getDefaultAdapter().isEnabled())
					{
						BluetoothAdapter.getDefaultAdapter().enable();
					}
					
					String andriod_code = mDeviceArray.get(0).getString("andriod_code");
					if(andriod_code == null || andriod_code.length() == 0)
					{
						showQuery();
					}
					else
					{
						BluetoothDevice localBluetoothDevice = ((DemoApp)getApplicationContext()).mBluetoothAdapter
								.getRemoteDevice(andriod_code);
						localBluetoothDevice.connectGatt(MainPageActivity.this, false, ((DemoApp)getApplicationContext()).mGattCallback);
						startTimer();
					}
				}
				catch(Exception e)
				{
					ToastUtil.showToastWithAlertPic("连接失败");
				}
				
				return;
			}
			else 
			{
				JSONArray array = mArray.getJSONObject(mSelected).getJSONArray("devices");
				int count = array.size();
				for(int i = 0; i < count; i++)
				{
					JSONObject obj = array.getJSONObject(i);
					List<BluetoothGatt> list = ((DemoApp)getApplicationContext()).deviceInfo;
					int size = list.size();
					for(int j = 0; j < size; j++)
					{
						try
						{
							if(list.get(j).getDevice().getAddress().equals(obj.getString("andriod_code")))
							{
								showWaiting("设备连接断开");
								startTimer();
								
								mManulDisconnect = true;
								list.get(j).disconnect();
								
								((DemoApp)getApplicationContext()).mSafeArray.add(
										String.valueOf(mArray.getJSONObject(mSelected).getString("childid")));
								changeStatus();
							}
						}
						catch(Exception e){}
					}
				}
			}
			break;
		}
	}

	Timer mTimer = null;
	void startTimer()
	{
		if(mTimer != null)
		{
			mTimer.cancel();
			mTimer = null;
		}
		
		final Handler handle = new Handler()
		{
			public void handleMessage(Message msg)
			{
				disMissDailog();
				if(((DemoApp)getApplicationContext()).mSafeArray.contains(
						String.valueOf(mArray.getJSONObject(mSelected).getString("childid"))) && !mManulDisconnect)
				{
					((DemoApp)getApplicationContext()).mSafeArray.remove(
							String.valueOf(mArray.getJSONObject(mSelected).getString("childid")));
					changeStatus();
				}	
			}
		};
		
		mTimer = new Timer();
		mTimer.schedule(new TimerTask()
		{
			@Override
			public void run() {
				handle.sendEmptyMessage(0);
			}
		}, 10000);
	}
	
	private File mPhotoFile;
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;
		Bitmap bitmap = null;
		if (resultCode == RESULT_OK) {
			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			
			bitmap = Utils.scalePic(bitmap, 240, 240);
			
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			((ImageView) findViewById(R.id.c_icon)).setImageBitmap(bitmap);
			sendUpdateHttpRequest();
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void sendUpdateHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					sendHttpRequest();
				} 
				else if (ruser.getString("state").equals("2")) 
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "updateChildInfo");
		if(mArray == null || mArray.size() == 0)
		{
			params.put("childname", "小兔乖乖");
			params.put("userid", PreferencesUtils.getString(this, "userid"));
		}
		else
		{
			params.put("childid", mArray.getJSONObject(mSelected).getString("childid"));
		}
		
		try {
			if (mPhotoFile != null)
				params.put("filename0", mPhotoFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		MgqRestClient.post(Constants.SETTING, params, loginHandler);
	}

	private void sendHttpRequest() {
		boolean show = false;
		if(mArray == null) show = true;
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					mArray = JSON.parseObject(response).getJSONArray("data");
				}
				else if (ruser.getState().equals("2")) 
				{
					showExitDialog();
				} 
				else {
					mArray = null;
				}
				
				changeStatus();
			}
		};
		// -----------------------

		RequestParams params = new RequestParams();
		params.put("act", "getMyChildList");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		MgqRestClient.get(Constants.DEVICEMGT, params, loginHandler);
	}
	
	 private long mExitTime;
	 public boolean onKeyDown(int keyCode, KeyEvent event) 
	 {
		 if (keyCode == KeyEvent.KEYCODE_BACK) {
			 if ((System.currentTimeMillis() - mExitTime) > 2000) 
			 {
				 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				 mExitTime = System.currentTimeMillis();	
			 } else {
				 finish();
			 }
			 return true;
		 }
		 return super.onKeyDown(keyCode, event);
	 }

	 
	 private GestureDetector mGestureDetector = null;
	 
	 @Override
	 public boolean onDown(MotionEvent arg0) {
		 return false;
	 }

	 @Override
	 public boolean onFling(MotionEvent e1, MotionEvent e2, float arg2,
			 float arg3) {
		 float x = e2.getX() - e1.getX();  
         float y = e2.getY() - e1.getY();  
         float x_limit = 20;  
         float x_abs = Math.abs(x);  
         float y_abs = Math.abs(y);  
         if(x_abs >= y_abs){  
             //gesture left or right  
             if(x > x_limit || x < -x_limit){  
                 if(x>0)
                 {  
                     //right  
                	 if(mSelected > 0) 
                	 {
                		 mSelected--;
                		 changeStatus();
                	 }
                 }
                 else if(x<=0)
                 {    
                	 if(mSelected < mArray.size() - 1) 
                	 {
                		 mSelected++;
                		 changeStatus();
                	 }
                 }  
             }  
         }
		 
		 return false;
	 }

	 @Override
	 public void onLongPress(MotionEvent arg0) {
			
	 }

	 @Override
	 public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			 float arg3) {
		 return false;
	 }

	 @Override
	 public void onShowPress(MotionEvent arg0) {
		 
	 }

	 @Override
	 public boolean onSingleTapUp(MotionEvent arg0) {
		 return false;
	 }

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		mGestureDetector.onTouchEvent(arg1);
		return true;
	}
}
